import {HomeHttp} from '../../../api/home.js'
import {GoodsHttp} from '../../../api/goods.js'
import {StoreHttp} from '../../../api/store.js'
import {CartHttp} from '../../../api/cart.js'
import {
    cartDiscountsMap,
    cartListMap,
    cartRecommendGoodMap,
    storeGoodsDetailsMap,
    storeInfoMap
} from '../../../utils/dataMap.js'
import {throttle} from '../../../utils/vutils'
import utils from "../../../utils/utils";
import User from "../../../utils/user";

const homeModel = new HomeHttp();
const goodsModel = new GoodsHttp();
const cartModel = new CartHttp();
const storeModel = new StoreHttp();
const app = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        initUser: true,
        goodsId: 0, // 商品Id
        storeId: 0, // 店铺Id
        storeInfo: {}, // 店铺信息
        goodsInfo: {}, // 商品信息
        goodsSwiper: [], // 商品轮播图
        goodsDetailsImgs: [], // 商品详情图
        needGoodsList: [], // 配套商品列表
        cartList: [], // 购物车列表
        cartDiscountsInfo: {}, // 购物车计算优惠信息
        isStoreOpen: true, // 店铺是否营业
        isLike: false, // 商品是否收藏
        isShowTabbarMore: false, // 是否显示tabbar更多操作
        isClearingBtnClick: false, // 结算按钮是否点击
        isShowCartAlertParent: true, // 是否控制显示购车提示
        isShowCartAlert: false, // 是否显示购物车提示
        isShowGoodsSkuPopup: false, // 是否显示商品规格弹窗
        currentSwiper: 1, // 当前轮播图 index
        addType: 1, // 弹出规格选择之后操作类型
        windowWidth: 0, // 屏幕宽度
        colorCls: "",//标题前面的颜色
    },

    async initPage(options) {
        let systemInfo = wx.getSystemInfoSync();
        if (options.id) {
            this.setData({
                windowWidth: systemInfo.windowWidth,
                goodsId: options.id,
                storeId: options.storeId,
            });
        } else {
            utils.msg('商品信息错误!');
            setTimeout(function () {
                wx.navigateBack();
            }, 1500);
        }
        await this.httpGetYddGoodsDetails(); // 获取商品信息
        if (options.hasOwnProperty('ekey')) {
            utils.UserUv(options.ekey);
            User.UvTrackPut(options.ekey);
        }
    },

    // 生命周期函数--监听页面显示
    onShow: function () {
        this.setData({
            userInfo: app.globalData.userInfo
        });
        if (this.data.userInfo && this.data.userInfo.uid && this.data.store_id) {
            this.httpGetCartList() // 请求店铺购物车
        }
    },

    // swiper change事件
    onChangeSwiper: function (e) {
        this.setData({
            currentSwiper: e.detail.current + 1
        })
    },

    async onPullDownRefresh() {
        if (this.data.initUser === false) {
            return false;
        }
        await this.httpGetYddGoodsDetails(); // 获取商品信息
    },

    // 添加到购物车
    onAddCart: throttle(function (event) {
        if (!(this.data.userInfo && this.data.userInfo.uid)) {
            this.setData({
                openLogin: true,
                initUser: false
            })
            return
        }
        const {
            goodsInfo,
            storeId,
            goodsId
        } = this.data
        if (goodsInfo.goodsStatus !== 1) return;
        if (goodsInfo.skuType === 1) {
            // 单规格商品
            if (goodsInfo.goodsSourceType === 1) {
                app.event.emit('addCartAnimation', {
                    x: event.touches[0].clientX,
                    y: event.touches[0].clientY
                })
            }
            this.singleSkuGoodsAddCart()
        } else if (goodsInfo.skuType === 2) {
            // 多规格商品 - 打开规格选择弹窗
            this.setData({
                isShowGoodsSkuPopup: true
            })
        }
    }, 500, {
        immediate: true
    }),

    // ===========================================================================================
    // 加入购物车以及结算

    // 单规格商品 - 加入购物车
    singleSkuGoodsAddCart() {
        const {
            goodsInfo,
            storeId,
            goodsId
        } = this.data
        const {
            serviceCenterId
        } = this.data.storeInfo
        if (goodsInfo.goodsSourceType === 1) {
            // 商品来源 --- 自营
            let addCartInfo = {
                goods: [{
                    goodsThumbnailUrl: goodsInfo.goodsThumbnailImg,
                    goodsTitle: goodsInfo.goodsName,
                    skuId: goodsInfo.singleSku.goods_sku_id,
                    spuId: goodsId,
                    skuAmount: 1,
                }],
                storeId: storeId,
                userId: this.data.userInfo.uid
            }
            this.httpAddCartGoods(addCartInfo);
        } else {
            // 商品来源 --- 1688
            const {
                goods_sku_id
            } = goodsInfo.singleSku
            let cartListArr = [{
                // cart_id: item.cartId,
                sku_id: goods_sku_id,
                spu_id: goodsId,
                amount: 1,
            }]
            wx.navigateTo({
                url: `/pages/goods/pendingOrder/pendingOrder?id=${JSON.stringify(cartListArr)}&storeId=${storeId}&serviceId=${serviceCenterId}&type=3`
            });
        }
    },

    // 多规格商品 - 选择商品规格 - 加入购物车
    onSkuAddCart(event) {
        const {
            goodsInfo
        } = this.data
        if (goodsInfo.goodsSourceType === 1) {
            // 商品来源为巷友 --- 加入购物车
            let addCartInfo = {
                goods: [event.detail],
                storeId: this.data.storeId,
                userId: this.data.userInfo.uid
            }
            this.httpAddCartGoods(addCartInfo).then((res) => {
                this.setData({
                    isShowGoodsSkuPopup: false
                })
            })
        } else {
            // 商品来源为1688 --- 立即购买
            const {
                storeId,
                serviceCenterId
            } = this.data.storeInfo
            let cartListArr = [{
                // cart_id: item.cartId,
                sku_id: event.detail.skuId,
                spu_id: event.detail.spuId,
                amount: event.detail.skuAmount,
            }]
            wx.navigateTo({
                url: `/pages/goods/pendingOrder/pendingOrder?id=${JSON.stringify(cartListArr)}&storeId=${storeId}&serviceId=${serviceCenterId}&type=3`
            });
        }

    },

    // 选择商品规格 - 关闭商品规格弹出层
    onCloseSkuPopup() {
        this.setData({
            isShowGoodsSkuPopup: false
        })
    },

    // 购物栏 - 结算
    onClearingCart() {
        const {
            cartList,
            storeId,
            needGoodsList,
            isClearingBtnClick
        } = this.data;
        let serviceCenterId = this.data.storeInfo.serviceCenterId;
        const navToClearing = function () {
            let cartListArr = cartList
                .map((item) => {
                    return {
                        cart_id: item.cartId,
                        sku_id: item.goodsSkuId,
                        spu_id: item.goodsSpuId,
                        amount: item.currentNum,
                    }
                });
            wx.navigateTo({
                url: `/pages/goods/pendingOrder/pendingOrder?id=${JSON.stringify(cartListArr)}&storeId=${storeId}&serviceId=${serviceCenterId}`
            });
        };
        if (cartList.length === 0) return
        if (needGoodsList.length !== 0) {
            if (isClearingBtnClick) {
                navToClearing()
            } else {
                this.setData({
                    isShowCartAlert: true,
                    isClearingBtnClick: true
                })
            }
        } else {
            navToClearing()
        }
    },

    // 购物栏提示 - 取消
    onCartAlertCancel() {
        this.setData({
            isShowCartAlertParent: false
        })
    },

    // 购物栏提示 - 确定
    onCartAlertConfirm() {
        const {
            needGoodsList,
            storeId
        } = this.data
        let addCartGoodsInfo = needGoodsList.map(item => {
            return {
                goodsThumbnailUrl: item.goodsImg,
                goodsTitle: item.goodsName,
                skuId: item.goodsSkuId,
                spuId: item.goodsSpuId,
                skuAmount: 1
            }
        })
        let addCartInfo = {
            goods: addCartGoodsInfo,
            storeId: this.data.storeId,
            userId: this.data.userInfo.uid
        }
        this.httpAddCartGoods(addCartInfo).then(() => {
            this.setData({
                needGoodsList: [],
                isShowCartAlert: false
            })
        })
    },

    // 清空购物车
    onClearCartList() {
        storeModel.deleteCartGoods({
            store_id: this.data.storeId
        }).then((res) => {
            // this.setData({
            //   isShowCartAlert: false,
            //   isClearingBtnClick: false
            // })
            this.httpGetCartList()
        })
    },

    // 添加到购物车
    httpAddCartGoods(param) {
        return storeModel.addGoodsToStoreCart(param).then((res) => {
            //utils.msg('已加入购物车！')
            this.httpGetCartList()
        }).catch((err) => {
            if (err.code === 2007) {
                utils.msg('请登录后操作！')
            }
        })
    },

    // 修改购物车商品数量
    onChangeStepper(event) {
        const {
            goods
        } = event.detail
        storeModel.addGoodsNumToStoreCart({
            goods: [goods],
            storeId: this.data.storeId,
            userId: this.data.userInfo.uid
        }).then((res) => {
            this.httpGetCartList()
        })
    },

    // tabbar - 更多
    onTabbarMore() {
        this.setData({
            isShowTabbarMore: !this.data.isShowTabbarMore
        })
    },

    // tabbar - 关闭tabbar更多弹出
    onCloseTabbarMore() {
        if (this.data.isShowTabbarMore) {
            this.setData({
                isShowTabbarMore: false
            })
        }
    },

    // tabbar - 收藏
    onTabbarLove() {
        if (this.data.isLike) {
            this.httpCancelGoodsLike()
        } else {
            this.httpAddGoodsLike()
        }
    },

    // 监听页面滚动
    onPageScroll() {
        this.onCloseTabbarMore()
    },

    // 获取购物车列表
    httpGetCartList() {
        return storeModel.getStoreCartList({
            storeId: this.data.storeId,
            userId: this.data.userInfo.uid
        }).then((res) => {
            if (!res.skuList || (res.skuList && res.skuList.length === 0)) {
                this.setData({
                    cartDiscountsInfo: cartDiscountsMap(res),
                    cartList: res.skuList ? cartListMap(res.skuList) : [],
                    needGoodsList: res.cartRecommendGoods ? cartRecommendGoodMap(res.cartRecommendGoods) : [],
                    isShowCartAlert: false,
                    isClearingBtnClick: false
                })
            } else {
                this.setData({
                    cartDiscountsInfo: cartDiscountsMap(res),
                    cartList: res.skuList ? cartListMap(res.skuList) : [],
                    needGoodsList: res.cartRecommendGoods ? cartRecommendGoodMap(res.cartRecommendGoods) : []
                })
            }
        })
    },

    // 获取巷友商品详情
    httpGetYddGoodsDetails() {
        const {
            goodsId,
            storeId
        } = this.data;
        let self = this;
        // wx.showNavigationBarLoading();
        goodsModel.getYddGoodsDetails({
            goods_id: goodsId,
            store_id: storeId
        }).then((res) => {
            // wx.hideNavigationBarLoading();
            wx.stopPullDownRefresh();
            wx.setNavigationBarTitle({
                title: res.goods_title
            });
            let storeInfoDataMap = storeInfoMap(res.store_info)
            let storeGoodsDataMap = storeGoodsDetailsMap(res)

            //设置分享金额颜色
            let map = {
                '0.03': '03', //'#a8d091',
                '0.05': '05', //'#528139',
                '0.07': '07', //'#9dc4eb',
                '0.1': '10', //'#1c517d',
                '0.10': '10', //'#1c517d',
                '0.15': '15', //'#ffc000',
                '0.20': '20', //'#be0002',
                '0.2': '20', //'#be0002',
            }
            let color = "";
            if (res.hasOwnProperty('commission2') && map.hasOwnProperty(res.commission2)) {
                color = 'label-color label-' + map[res.commission2]
            }
            this.setData({
                colorCls: color,
                storeId: res.store_info.store_id, // 店铺ID
                storeInfo: storeInfoDataMap, // 店铺信息.
                isStoreOpen: storeInfoDataMap.isOpening, // 店铺是否营业
                goodsInfo: storeGoodsDataMap, // 商品信息
                goodsSwiper: res.goods_gallery_urls, // 商品轮播图
                goodsDetailsImgs: res.goods_detail, // 商品详情
                isLike: storeGoodsDataMap.isLike // 商品是否收藏
            });
            if (this.data.userInfo && this.data.userInfo.uid) {
                this.httpGetCartList(); // 请求店铺购物车
            }
            self.shareOption['title'] = self.data.goodsInfo.goodsName;
            self.shareOption['path'] = `/pages/goods/mmallGoodsDetails/mmallGoodsDetails?id=${goodsId}&storeId=${storeId}`;
            self.shareOption['imageUrl'] = res.goods_gallery_urls[0];
            console.log(goodsId);
            utils.request({
                url: 'wxgroup/WxGoodsPoster',
                data: {
                    "goods_id": goodsId,
                },
                loading: 2,
                handle: true,
                callback: function (result) {
                    self.shareOption['imageUrl'] = result['res'];
                }
            });
        });
    },

    // 将商品添加收藏
    httpAddGoodsLike() {
        return goodsModel.addGoodsLike({
            good_id: this.data.goodsId
        }).then((res) => {
            this.setData({
                isLike: true
            })
        })
    },

    // 将商品移除收藏
    httpCancelGoodsLike() {
        return goodsModel.cancelGoodsLike({
            good_ids: [this.data.goodsId]
        }).then((res) => {
            this.setData({
                isLike: false
            })
        })
    },
    //保存图片下来
    onShareImg() {
        const {
            goodsId
        } = this.data;
        let self = this;
        if (!(this.data.userInfo && this.data.userInfo.uid)) {
            this.setData({
                openLogin: true,
                initUser: false
            })
            return
        }
        let callback = function (path) {
            wx.getImageInfo({
                src: path,
                success(res) {
                    wx.saveImageToPhotosAlbum({
                        filePath: res.path,
                        success(res) {
                            utils.msg('分享图片保存成功！');
                        },
                        fail(res) {
                            utils.msg('分享图片保存失败，请稍候再试！');
                        }
                    });
                },
                fail(res) {
                    utils.msg('分享图片拉取失败，请稍候再试！');
                }
            });
        };
        utils.request({
            url: 's/wxgroup/GetWxPoster',
            data: {
                "goods_id": goodsId,
            },
            loading: true,
            handle: true,
            callback: function (result) {
                let path = result['res']['img'];
                wx.getSetting({
                    success(res) {
                        if (!res.authSetting['scope.writePhotosAlbum']) {
                            wx.authorize({
                                scope: 'scope.writePhotosAlbum',
                                success() {
                                    callback(path);
                                },
                                fail() {
                                    utils.msg('您拒绝了保存权限，无法下载到相册');
                                }
                            })
                        } else {
                            callback(path);
                        }
                    },
                    fail(res) {
                        utils.msg('获取权限设置失败，请稍候再试！');
                    }
                });
            }
        });
    },
});